package com.taotao.portal.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.taotao.portal.httpclientService.HttpClientService;

@Service
public class IndexService {

	@Value("${MANAGE_URL}")
	private String MANAGE_URL;
	
	@Value("${INDEX_BIGAD_URL}")
	private String INDEX_BIGAD_URL;
	
	@Autowired
	private HttpClientService service;
	
	private static final ObjectMapper MAPPER = new ObjectMapper();
	
	
	public String getIndexAd(){
		String url = MANAGE_URL + INDEX_BIGAD_URL;
		try {
			String jsonData = service.doGet(url);
			JsonNode jsonNode = MAPPER.readTree(jsonData);
			ArrayNode nodes = (ArrayNode) jsonNode.get("rows");
			List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
			for(JsonNode node : nodes){
				Map<String, Object> m = new LinkedHashMap<>();
				m.put("srcB", node.get("pic").asText());
				m.put("height", 240);
				m.put("alt", node.get("title").asText());
				m.put("width", 670);
				m.put("src", node.get("pic2").asText());
				m.put("widthB", 550);
				m.put("href", node.get("url").asText());
				m.put("heightB", 240);
				result.add(m);
			}
			return MAPPER.writeValueAsString(result);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}

}
